package com.qf.air.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.air.exception.AirEx;

import java.io.IOException;

/**
 * @author ASUS
 * @version V1.0
 * @Project air
 * @Package com.qf.air.util
 * @Date 2021/11/1 19:39
 */
public class JSONUtil {

    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 对象转JSON字符串
     * @param obj
     * @return
     */
    public static String obj2JSON(Object obj){
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw  new AirEx("当前对象无法序列化为JSON字符串,obj="+obj,500);
        }
    }

    /**
     * JSON字符串转对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(String json,Class<T> clazz){
        try {
            return OBJECT_MAPPER.readValue(json,clazz);
        } catch (IOException e) {
            throw  new AirEx("当前JSON字符串无法序列化为对象,json="+json,500);
        }
    }
}
